package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.rmi.server.ExportException;

@Slf4j
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserLikeApi userLikeApi;



    /**
     * 保持个人信息
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 登录注册-完善个人资料-上传头像
     *
     * @param headPhoto
     * @param id
     * @throws IOException
     */
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);

        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }

    }

    /**
     * 根据id查寻
     *
     * @param id
     * @return
     */
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    /**
     * 更新
     *
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 更新头像
     *
     * @param headPhoto
     */
    public void updateUserHead(MultipartFile headPhoto) throws IOException {
        User user = userApi.findById(UserHolder.getUserId());

        try {

            // 获取用户上传的文件名
            String filename = headPhoto.getOriginalFilename();
            String headerUrl = null;
            if ("".equals(filename) || filename != null) {
                // 将头像文件上传到oss中
                headerUrl = ossTemplate.upload(filename, headPhoto.getInputStream());
            }
            // 调用人脸检测,检测用户上传图片是否有人脸信息
            if (!aipFaceTemplate.detect(headerUrl)) {
                throw new BusinessException(ErrorResult.faceError());
            }
            // 获取userInfo
            UserInfo userInfo = userInfoApi.findById(user.getId());
            // 获取原来的头像地址
            String oldFilename = userInfo.getAvatar();
            // 更新头像url
            userInfo.setAvatar(headerUrl);
            // 获取用户id并设置
            userInfo.setId(user.getId());
            // 调用Api更新用户信息
            userInfoApi.update(userInfo);
            // 删除旧头像
            ossTemplate.deleteFile(oldFilename);
        } catch (IOException e) {
            log.error("上传头像失败", e);
            throw new ExportException("上传头像失败");
        }

    }

    /**
     *统计好友,喜欢,粉丝数量
     * @return
     */
    public CountsVo counts() {
        Long userId = UserHolder.getUserId();

        Long eachLoveCount = friendApi.findCountByUserId(userId);
        Long countFans = userLikeApi.countFans(userId);
        Long countLoves = userLikeApi.countLoves(userId);
        CountsVo vo = new CountsVo();
        vo.setEachLoveCount(eachLoveCount);
        vo.setFanCount(countFans);
        vo.setLoveCount(countLoves);
        return vo;
    }

}
